import os
import json
import types  # ✅ 用于识别 mappingproxy 类型
from docling.document_converter import DocumentConverter

def serialize_obj(obj):
    """将对象递归转换为 JSON 可序列化结构"""
    if isinstance(obj, dict):
        return {k: serialize_obj(v) for k, v in obj.items()}
    elif isinstance(obj, list):
        return [serialize_obj(i) for i in obj]
    elif isinstance(obj, types.MappingProxyType):  # ✅ 处理 mappingproxy
        return serialize_obj(dict(obj))
    elif hasattr(obj, "__dict__"):
        return serialize_obj(vars(obj))
    else:
        return obj

# ✅ 文件路径
source = "data/初赛A榜/赛题制度文档/国金资料/1--中国银行业监督管理委员会关于印发农村信用社省（自治区直辖市）联合社管理暂行规定的通知银监发200314号.docx"
if not os.path.exists(source):
    raise FileNotFoundError(f"未找到文件: {source}")

# ✅ 文档解析
converter = DocumentConverter()
result = converter.convert(source)
doc = result.document

# ✅ 序列化并保存 JSON
with open("docling结构.json", "w", encoding="utf-8") as f:
    json.dump(serialize_obj(doc), f, ensure_ascii=False, indent=2)

print("✔ doc.document 已成功保存为结构化 JSON")
